#include "viewport.h"
#include "googletile.h"

ViewPort::ViewPort()
{
}

ViewPort::ViewPort(QRect extent)
{
	centerPt = GeoPoint(0, 0);
	zoomLevel = 0;
	viewPortRect = extent;
}

void ViewPort::UpdateGeoExtent()
{
	resolution = GoogleTile::GetResolutionByLevel(zoomLevel);
	geoExtent.minx = centerPt.x - resolution * viewPortRect.width() / 2;
	geoExtent.maxx = centerPt.x + resolution * viewPortRect.width()/2;
	geoExtent.maxy = centerPt.y + resolution * viewPortRect.height()/2;
	geoExtent.miny = centerPt.y - resolution * viewPortRect.height()/2;
}

void ViewPort::UpdateIndexRange()
{
    QPoint ul = COMFUNC_DegreeToXYIndex(geoExtent.minx, geoExtent.maxy, zoomLevel);
    QPoint br = COMFUNC_DegreeToXYIndex(geoExtent.maxx, geoExtent.miny, zoomLevel);
    tileIndexRange.setTopLeft(ul);
    tileIndexRange.setBottomRight(br);
}

void ViewPort::Update()
{
    UpdateGeoExtent();
    UpdateIndexRange();
}

QRect ViewPort::getTileIndexRange() const
{
    return tileIndexRange;
}

void ViewPort::setTileIndexRange(const QRect &value)
{
    tileIndexRange = value;
}

GeoExtent ViewPort::getGeoExtent() const
{
    return geoExtent;
}

void ViewPort::setGeoExtent(const GeoExtent &value)
{
    geoExtent = value;
}

int ViewPort::getZoomLevel() const
{
	return zoomLevel;
}

void ViewPort::setZoomLevel(int value)
{
	zoomLevel = value;
}

QRect ViewPort::getViewPortRect() const
{
	return viewPortRect;
}

void ViewPort::setViewPortRect(const QRect &value)
{
	viewPortRect = value;
    Update();
}


void ViewPort::ZoomIn()
{
	zoomLevel += 1;
    if(MAX_LEVEL < zoomLevel)
        zoomLevel = MAX_LEVEL;
    Update();
}

void ViewPort::ZoomOut()
{
	zoomLevel -= 1;
	if(0 > zoomLevel)
	{
		zoomLevel = 0;
	}
    Update();
}

void ViewPort::Move(int deltaX, int deltaY)
{
	centerPt.x += -deltaX * resolution;
	centerPt.y += deltaY * resolution;
    Update();
}
